package com.seveneight.baijiesteward.ui.user.fragment.identify;

import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseFragmentBack;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.ui.user.fragment.IdentifyFragment;
import com.seveneight.baijiesteward.utils.FileUtil;
import com.seveneight.baijiesteward.utils.GlideLoader;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.MDialog;
import com.seveneight.baijiesteward.utils.PathManagetUtil;
import com.seveneight.baijiesteward.utils.ToastUtil;

import java.io.File;

/**
 * Created by user1 on 2018/2/23.
 */

public class IdentifyFragment1 extends BaseFragmentBack implements View.OnClickListener {

    private static final int REQUEST_CODE_CAMERA = 102;
    private ImageView iv_step1;
    private EditText tv_name;
    private EditText tv_idNumber;
    private MDialog dialog;
    private String savePath;

    @Override
    protected int getContentView() {
        return R.layout.identify1;
    }

    @Override
    protected void initView() {
        setSwipeBackEnable(false);
        iv_step1 = findView(R.id.iv_step1);
        tv_name = findView(R.id.tv_name);
        tv_idNumber = findView(R.id.tv_idNumber);
        dialog = new MDialog(mContext, "正在识别...");
    }

    @Override
    protected void initData() {
        initCameraNativeHelper();
    }


    @Override
    protected void setListener() {
        iv_step1.setOnClickListener(this);
        tv_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                IdentifyFragment.RealName=tv_name.getText().toString();
                findView(R.id.edit_layout).setVisibility(View.VISIBLE);
            }
        });
        tv_idNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                IdentifyFragment.IdCardNo=tv_idNumber.getText().toString();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_step1:
                scanIdCard();
                break;
        }
    }

    private void scanIdCard() {
        final String fileName = System.currentTimeMillis() + ".jpg";
        savePath = PathManagetUtil.getSavePath() + fileName;
        Intent intent = new Intent(mContext, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                savePath);
        intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE,
                true);
        intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL,
                true);
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            dialog.showLoadingDialog();
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                LogUtil.d("filePath:"+savePath);
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, savePath);
                    } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, savePath);
                    }
                }
            }
        }
    }

    private void recIDCard(String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(80);

        OCR.getInstance().recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    refreshUI(result);
                }
            }

            @Override
            public void onError(OCRError error) {
                alertText(error.getMessage());
            }
        });
    }

    private void refreshUI(IDCardResult result) {
        IdentifyFragment.STEP = 2;
        IdentifyFragment.IMGSPATH1 = savePath;
        GlideLoader.displayImg(mContext, savePath, iv_step1);
        tv_name.setText(result.getName().toString());
        tv_idNumber.setText(result.getIdNumber().toString());
        dialog.hideDialog();
    }

    private void alertText(final String message) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.hideDialog();
                ToastUtil.show(mContext, message);
            }
        });
    }

    private void initCameraNativeHelper() {
        CameraNativeHelper.init(mContext, OCR.getInstance().getLicense(),
                new CameraNativeHelper.CameraNativeInitCallback() {
                    @Override
                    public void onError(int errorCode, Throwable e) {
                        String msg;
                        switch (errorCode) {
                            case CameraView.NATIVE_SOLOAD_FAIL:
                                msg = "加载so失败，请确保apk中存在ui部分的so";
                                break;
                            case CameraView.NATIVE_AUTH_FAIL:
                                msg = "授权本地质量控制token获取失败";
                                break;
                            case CameraView.NATIVE_INIT_FAIL:
                                msg = "本地质量控制";
                                break;
                            default:
                                msg = String.valueOf(errorCode);
                        }
                        LogUtil.d(msg);
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CameraNativeHelper.release();
    }
}
